package cn.shop.lib_common;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.TypedValue;
import android.view.View;
import android.widget.Toast;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2016/4/7.
 * 工具类
 */
public class ComUtils {
    private static ExecutorService mPool = Executors.newCachedThreadPool();
    private static Handler mHandler = new Handler(Looper.getMainLooper());
    private static Toast mToast;

    public static Handler getHandler() {
        return mHandler;
    }

    public static void runOnThread(Runnable task) {
        mPool.execute(task);
    }

    public static void runOnMainThread(Runnable task) {
        mHandler.post(task);
    }

    public static void showSafeToast(final Context context, final String text) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static void showSingleToast(Context context, String text) {
        if (mToast == null) {
            mToast = Toast.makeText(context, text, Toast.LENGTH_LONG);
        }
        mToast.setText(text);
        mToast.show();
    }

    public static float dpToPx(Context context, float dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
    }

    public static String getCurTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    public static int getStatusBarWidth(View view) {
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        return rect.top;
    }

    public static SpannableString getShowPrice(float price) {
        // 删除线 StrikethroughSpan()
        // 黑体 new StyleSpan(Typeface.BOLD)
        String priceStr = new DecimalFormat("0.00").format(price);
        SpannableString string = new SpannableString("￥" + priceStr);
        string.setSpan(new ForegroundColorSpan(Color.RED), 0, string.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        string.setSpan(new RelativeSizeSpan(1.2f), 0, 0, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        string.setSpan(new RelativeSizeSpan(1.5f), 1, string.length() - 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        string.setSpan(new RelativeSizeSpan(0.8f), string.length() - 2, string.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return string;
    }
}
